/* 
 * This program is free software; you can redistribute it and/or modify 
 * it under the terms of the GNU General Public License as published by 
 * the Free Software Foundation; either version 3 of the License, or 
 * (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful, but 
 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY 
 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 
 * for more details.
 * 
 * You should have received a copy of the GNU General Public License along 
 * with this program; if not, write to the Free Software Foundation, Inc., 
 * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
 */

#include <QSettings>
#include "filtertext.h"
#include "filterwipe.h"
#include "filterlist.h"
#include "log.h"

namespace Wishmaster
{
	FilterList::FilterList()
	{
		QSettings settings;
		if(settings.value("filtration/wipefilter", true).toBool())
		{
			FilterPtr wipe = FilterPtr(new FilterWipe("wipe"));
			m_filters.append(wipe);
		}
	}

	FilterList::~FilterList()
	{
	}

	QStringList FilterList::save()
	{
		QStringList s;
		foreach(FilterPtr filter, m_filters)
		{
			s.append(filter->serialize());
		}
		return s;
	}

	void FilterList::load(const QStringList& list)
	{
		foreach(QString s, list)
		{
			QRegExp rx("^(\\w+)@([^:]+)://(.*)$");
			rx.setMinimal(true);
			if(rx.exactMatch(s))
			{
				QString id = rx.cap(1);
				QString name = rx.cap(2);
				FilterPtr prototype = m_prototypes.value(id);
				if(!prototype.isNull())
				{
					FilterPtr newfilter = prototype->clone(name);
					newfilter->deserialize(rx.cap(3));
					m_filters.append(newfilter);
				}
			}
			else
			{
				log(llError, "Invalid filter pattern: %s", qPrintable(s));
			}
		}
	}

	FilterPtr FilterList::filter(int index)
	{
		if(index < 0 || index >= m_filters.size())
			return FilterPtr();
		return m_filters.at(index);
	}

	void FilterList::deleteFilter(int index)
	{
		if(index < 0 || index >= m_filters.size())
			return;
		m_filters.takeAt(index);
	}

	QStringList FilterList::listFilters()
	{
		QStringList s;
		foreach(FilterPtr filter, m_filters)
		{
			s.append(filter->name());
		}
		return s;
	}

	void FilterList::addTextFilter(const QString& name, const QString& pattern, bool cis)
	{
		FilterPtr filter(new FilterText(name, pattern, cis));
		m_filters.append(filter);
	}

	bool FilterList::check(const PostPtr& post)
	{
		foreach(const FilterPtr& filter, m_filters)
		{
			if(filter->check(post))
				return true;
		}
		return false;
	}

	bool FilterList::checkText(const QString& text)
	{
		foreach(const FilterPtr& filter, m_filters)
		{
			if(filter->checkText(text))
				return true;
		}
		return false;
	}

	void FilterList::addPrototype(FilterPtr proto)
	{
		if(proto.isNull())
			return;
		m_prototypes.insert(proto->id(), proto);
	}
}

